using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DocLibApp
{
    public partial class FormMain : FormBase
    {
        #region My Variables
        #region Static Variables
        private static SQLiteDB SQLiteDatabase = null;
        //private static AccessDB AccessDatabase = null;
        private static string CurrentUser = "";
        private static FormMain formMain;
        private static DataTable StaticValueList = new DataTable();
        private static string sDocumentPath = "";
        private static querybuilder myQueryBuilder = null;
        #endregion // Static Variables
        #endregion // My Variables

        #region Public Properties
        public static FormMain DocLibFormMain
        {
            get
            {
                return formMain;
            }
        }

        public static SQLiteDB DocLib_SQLite
        {
            get
            {
                return SQLiteDatabase;
            }
        }

        /// <summary>
        /// Query Builder
        /// </summary>
        public static querybuilder DocLib_QB
        {
            get
            {
                return myQueryBuilder;
            }
        }

        public static DataTable DocLibStaticValueList
        {
            get
            {
                return StaticValueList;
            }
        }

        public static string DocLib_DocumentPath
        {
            get
            {
                return sDocumentPath;
            }
        }

        public static string DocLib_CurrentUser
        {
            get
            {
                return CurrentUser;
            }
        }
        #endregion

        #region Initialization Main Form
        public FormMain(string user)
        {
            try
            {
                formMain = this;

                InitializeComponent();

                switchUser(user);

                InitializeApplication();
            }
            catch (System.Exception ex)
            {
                HandleEx(ex);
            }
        }

        private void InitializeApplication()
        {
            ReadSetting();

            //query builder
            myQueryBuilder = new querybuilder();

            InitializeSQLiteDatabaseFile();
            
            LoadStaticValueListFromDatabase();

            SetupGUI();

            ShowDialog();
        }

        private void switchUser(string username)
        {
            CurrentUser = username;
            StatusLabel_User.Text = username;
        }

        private void ReadSetting()
        {
            util.GetSettingHash(settingHash, def.FileName_DefaultConfig);

            SQLiteDatabaseFileName = GetSettingString(def.ck_DatabaseFileName_SQLite, SQLiteDatabaseFileName);
            DocumentPath = GetSettingString(def.ck_Document_File_Path, DocumentPath);

            sDocumentPath = DocumentPath;

            if (!System.IO.Directory.Exists(sDocumentPath))
            {
                ShowMessage("The folder that stores document (" + sDocumentPath + ") does not exist. It will be created.");

                System.IO.Directory.CreateDirectory(sDocumentPath);
            }
        }

        private void InitializeSQLiteDatabaseFile()
        {
            SQLiteDatabase = new SQLiteDB(SQLiteDatabaseFileName);

            SQLiteDatabase.OpenConnection();
        }

        private void LoadStaticValueListFromDatabase()
        {
            StaticValueList = SQLiteDatabase.GetDataTable(def.qry_stat_list,"temp");
        }

        private void SetupGUI()
        {
            string ProductName = GetAppCode("APP_TITLE");
            string ProductVersion = GetAppCode("APP_VERSION");

            MainFormTitle = ProductName + " v" + ProductVersion;

            StatusLabel_Date.Text = System.DateTime.Now.ToShortDateString();
            StatusLabel_Time.Text = System.DateTime.Now.ToLongTimeString();
            StatusLabel_Info.Text = "welcome to document management system";

            ProcessRegistrationInformation();

            LoadBackgroundImage();

            LoadRecentFileList();

            this.Text = MainFormTitle;
        }

        /// <summary>
        /// load list of recently open document in recent list
        /// </summary>
        private void LoadRecentFileList()
        {
            //recentDocumentsToolStripMenuItem
            System.Collections.Hashtable ht = doc_system.GetAList(def.RecentDocumentList_Group);

            foreach (string key in ht.Keys)
            {
                string desc = ht[key].ToString();

                System.Windows.Forms.ToolStripMenuItem aItem = new ToolStripMenuItem();

                aItem.Tag = key;
                aItem.Text = desc + " [" + key + "]";
                aItem.Click += new EventHandler(RecentDocMenuClick);

                recentDocumentsToolStripMenuItem.DropDownItems.Add(aItem);
            }
        }

        private void RecentDocMenuClick(object sender, EventArgs e)
        {
            if (sender is ToolStripItem)
            {
                ToolStripItem aitem = sender as ToolStripItem;
                if (aitem.Tag != null && !string.IsNullOrEmpty(aitem.Tag.ToString()))
                {
                    string doc_id = aitem.Tag.ToString();

                    OpenDocument(doc_id);
                }
            }
        }

        private void LoadBackgroundImage()
        {
            //load background image file
            string ImagePath = GetSettingString(def.ck_Background_Image_Path, "");
            string PrevImageFileName = GetSettingString(def.ck_Background_Image_Filename_Previous, "");

            string ImageFileName = util.GetRandomImageFile(ImagePath, "");

            if (!string.IsNullOrEmpty(ImageFileName) && System.IO.File.Exists(ImageFileName))
            {
                SaveSetting(def.ck_Background_Image_Filename_Previous, ImageFileName);

                Image MyImage = new Bitmap(ImageFileName);
                this.BackgroundImage = MyImage;
            }
        }

        /// <summary>
        /// Check license file and validate license etc
        /// </summary>
        private void ProcessRegistrationInformation()
        {
            if (System.IO.File.Exists(def.FileName_DefaultLicense))
            {
                //checking user license info by loading license file and parsing it
                List<string> info = doc_system.GetLicenseInfo(def.FileName_DefaultLicense);

                if (info.Count > 0)
                {
                    string lic_user = info[0];
                    string lic_company = info[1];
                    string lic_num = info[2];
                    string lic_key = info[3];

                    try
                    {
                        if (util.IfKeyIsValid(lic_user, lic_company, lic_num, lic_key))
                        {
                            MainFormTitle += " (Registered to: " + lic_user + " of " + lic_company + ")";

                            registrationToolStripMenuItem.Visible = false;
                        }
                        else
                            MainFormTitle += " (unregistered)";
                    }
                    catch (System.Exception)
                    {
                        ShowMessage("Invalid registration information.");
                    }
                }
            }
            else //no license file
            {
                MainFormTitle += " (unregistered)";
            }


        }
        #endregion //EO Initialization Main Form

        #region Form Events
        private void Application_Idle(Object sender, EventArgs e)
        {

            MessageBox.Show("You are in the Application.Idle event.");

        }

        private void myTimer_Tick(object sender, EventArgs e)
        {
            StatusLabel_Time.Text = System.DateTime.Now.ToLongTimeString();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //close SQLiteDatabase file
            if (SQLiteDatabase != null)
                SQLiteDatabase.CloseConnection();


            //save setting Hash if anything changed
            util.SaveSettingHash(settingHash, def.FileName_DefaultConfig);            
        }

        #region Private functions
        private void RunCommand(object sender, EventArgs e)
        {
            string tag = "";

            if (sender is ToolStripButton && (sender as ToolStripButton).Tag != null)
                tag = (sender as ToolStripButton).Tag.ToString();
            else if (sender is ToolStripMenuItem && (sender as ToolStripMenuItem).Tag != null)
                tag = (sender as ToolStripMenuItem).Tag.ToString();

            switch (tag.ToUpper())
            {
                case "LOGIN":
                    FormLogin fli = new FormLogin();
                    fli.ShowDialog();
                    if (fli.IsAuthenticated)
                    {
                        switchUser(fli.AuthenticatedUser);
                    }
                    break;
                case "LOGOUT":
                    Application.Restart();
                    break;
                case "BACKUPDATABASEFILE":
                    /*
                    string filename = SelectFile(0, "Backup Database File", "Zip files (*.zip)|*.zip", "backup_databasefile.zip");
                    if (!string.IsNullOrEmpty(filename))
                    {
                        wait_start("Backing up the document library data file (" + System.IO.Path.GetFileName(SQLiteDatabaseFileName) + ")...");
                        //need to close the sqlite connection before zipping file

                        FormMain.SQLiteDatabase.CloseConnection();
                        FormMain.SQLiteDatabase = null;
                        
                        util.ZipOneFile(SQLiteDatabaseFileName, SQLiteDatabaseFileName, "Backup of document library data file", "");

                        wait_end();
                    }
                     */
                    break;
                case "EXIT":
                    Application.Exit();
                    break;
                case "FILEIMPORT":
                    FormFileImport ffi = new FormFileImport();
                    OpenNewMdi(ffi);
                    break;
                case "DATABASE":
                    FormDatabase fdb = new FormDatabase();
                    OpenNewMdi(fdb);
                    break;
                case "SEARCHDOCUMENT":
                    FormSearchDoc fsd = new FormSearchDoc();
                    OpenNewMdi(fsd);
                    break;
                case "OPENDOCUMENT":
                    SelectDocumentToOpen();
                    break;
                case "BROWSE":
                    FormBrowse fb = new FormBrowse();
                    OpenNewMdi(fb);
                    break;
                case "ABOUT":
                    FormAbout fbs = new FormAbout();
                    fbs.ShowDialog();
                    break;
                case "ADDUSER":
                    FormUser fuser = new FormUser();
                    fuser.ShowCreateUser();
                    break;
                case "EDITUSER":
                    FormUser fuser2 = new FormUser();
                    fuser2.ShowEditUser(CurrentUser);
                    break;
                case "EDITANYUSER":
                    EditAnyUser();
                    break;
                case "TEST":
                    FormTest ft = new FormTest();
                    OpenNewMdi(ft);
                    break;
                case "REGISTRATION":
                    FormRegister fr = new FormRegister();
                    OpenNewMdi(fr);
                    break;
                case "BATCHPROCESS":
                    FormBatchProcess fbp = new FormBatchProcess();
                    OpenNewMdi(fbp);
                    break;
                case "CREATETEMPLATE":
                    FormTemplate ftmp = new FormTemplate();
                    ftmp.CreateNewTemplate();
                    OpenNewMdi(ftmp);
                    break;
                case "EDITTEMPLATE":
                    EditTemplate();
                    break;
                case "TABLECOLUMNS":
                    FormTableColumn ftc = new FormTableColumn();
                    OpenNewMdi(ftc);
                    break;
                case "SYSTEMCODE":
                    FormSystemCode fsc = new FormSystemCode();
                    OpenNewMdi(fsc);
                    break;
                case "CREATENEWROLE":
                    FormRole frl = new FormRole();
                    frl.CreateNewRole();
                    OpenNewMdi(frl);
                    break;
                case "EDITROLE":
                    EditRole();
                    break;
                case "PREFERENCES":
                    if (settingHash.Count > 0)
                    {
                        FormPreference fpr = new FormPreference();
                        fpr.LoadPreference(settingHash);
                        fpr.ShowDialog();

                        if (fpr.bSaveChanges)
                            settingHash = fpr.SaveSetting();
                    }
                    break;
                default:
                    break;
            }
        }

        private void EditTemplate()
        {
            string template_id = PickTemplate();

            if (!string.IsNullOrEmpty(template_id))
            {
                FormTemplate ftmp = new FormTemplate();
                ftmp.EditTemplate(template_id);
                OpenNewMdi(ftmp);
            }
        }

        private void EditAnyUser()
        {
            string user = PickUser();

            if (!string.IsNullOrEmpty(user))
            {
                FormUser fuser = new FormUser();
                fuser.ShowEditUser(user);
                OpenNewMdi(fuser);
            }
        }

        private void EditRole()
        {
            string role_id = PickRole();
            if (!string.IsNullOrEmpty(role_id))
            {
                FormRole ftmp = new FormRole();
                ftmp.EditRole(role_id);
                OpenNewMdi(ftmp);
            }
        }

        private void ShowInfo(string msg)
        {
            StatusLabel_Info.Text = msg;
        }
        #endregion //EO Private Functions

        #endregion Form Events //EO Form Events
    }
}